from datetime import datetime, date
from sqlalchemy import String, DateTime, Integer, DECIMAL, JSON, Date, Index, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from config.database import Base


class SpeechClientUsageDO(Base):
    """
    客户端用户使用统计表
    """
    __tablename__ = 'speech_client_usage'

    usage_id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True, comment='使用统计ID')
    client_user_id: Mapped[int] = mapped_column(Integer, ForeignKey('speech_client_user.client_user_id'), nullable=False, comment='客户端用户ID')
    usage_date: Mapped[date] = mapped_column(Date, nullable=False, comment='统计日期')
    total_requests: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment='总请求数')
    total_duration: Mapped[float] = mapped_column(DECIMAL(15, 2), nullable=False, default=0, comment='总音频时长（秒）')
    total_characters: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment='总识别字符数')
    model_usage: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict, comment='模型使用统计')
    api_calls: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment='API调用次数')
    success_rate: Mapped[float] = mapped_column(DECIMAL(5, 2), nullable=False, default=0, comment='成功率（%）')
    avg_response_time: Mapped[float] = mapped_column(DECIMAL(10, 3), nullable=False, default=0, comment='平均响应时间（秒）')
    error_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment='错误次数')
    peak_concurrent: Mapped[int] = mapped_column(Integer, nullable=False, default=0, comment='峰值并发数')
    create_time: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.now, comment='创建时间')
    update_time: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now, comment='更新时间')

    # 创建索引
    __table_args__ = (
        Index('idx_speech_client_usage_client_user_id', 'client_user_id'),
        Index('idx_speech_client_usage_usage_date', 'usage_date'),
        Index('uk_speech_client_usage_client_date', 'client_user_id', 'usage_date', unique=True),
    ) 